//  OpenCVDLL.cpp
//
//  OpenCV Wrapper functions for Mayhem
//
// (c) 2010 Microsoft Applied Sciences Group
// Author: Sven Kratz







#include "stdafx.h"

#include "OpenCVDLL.h"



using namespace OpenCVDLL;


 int OpenCVImageProvider::GetNumDevices()
			{
				return VI.listDevices();
			}

/// returns "list" of devicenames
/// device names a separated with ';' and then parsed in C# 
void  OpenCVImageProvider::EnumerateDevices(char * devices, int * numDevices)
{
	int nDevices = VI.listDevices();


	int offset = 0; 
	for (int i = 0 ; i < nDevices; i++)
	{
		int length = 0 ;
		char * dName = VI.getDeviceName(i);
		

		// determine length of string

		char nameBuf[64]; 

		length = strlen(dName); 

		if (length > 1)
		{
			strcpy(nameBuf, dName); 
			strncat(devices, dName, length);
			if ( i < nDevices -1)
			{
				strncat(devices,";",1);
			}
		}		
	}

	// hook up the pointer and the reference
	*numDevices = nDevices;
}

// stops and releases a given image device
void OpenCVImageProvider::StopCam(int device)
{
	VI.stopDevice(device);
}



 /*
 *   The OpenCVImageProvider provides image frames to all Mayhem events and reactions
 *
 */
 void OpenCVImageProvider::InitCam(int device, int width, int height)
			{


				int deviceID = device;
				printf("\tOpenCVImageProvider::InitCam -- starting \n");

				printf("\tOpenCVImageProvider::InitCam w%d h%d\n",width, height);
				int numDevices = VI.listDevices();
				if (device > numDevices)
					return;

				// set the correct deviceID
				deviceID = device;
				try
				{
					VI.setupDevice(device,width,height);

					// auto reconnect on freeze
					VI.setAutoReconnectOnFreeze(device, true, 2);
					width = VI.getWidth(device);
					height = VI.getHeight(device);

					// create buffer for image
					imageSize = VI.getSize(device);
					imageDataBuffer = new unsigned char[imageSize];

					// create current (global) camera image
					global_image = cvCreateImage(cvSize(width, height), 8, 3);	
				}
				catch (System::AccessViolationException^ avEx)
				{
					Debug::WriteLine("OpenCVImageProvider::InitCam AccessViolationException");
					Debug::WriteLine(avEx);
				}
				
			}

	  void OpenCVImageProvider::GetNextFrame(int deviceID, unsigned char * buffer)
	  {
		  // this should be called to prevent the cam from freezing
		  if(VI.isFrameNew(deviceID)){}
		  VI.getPixels(deviceID, buffer, false, true);
	  }

	  int OpenCVImageProvider::GetImageSize()
	  {
		  return imageSize;
	  }

	

 




